package com.school.controller;

import com.school.entity.User;
import com.school.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginForm, HttpSession session) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        Optional<User> userOpt = userService.findByUsername(username);
        Map<String, Object> result = new HashMap<>();
        if (userOpt.isPresent() && userService.checkPassword(userOpt.get(), password)) {
            session.setAttribute("user", userOpt.get());
            result.put("success", true);
            result.put("user", userOpt.get());
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }

    @PostMapping("/logout")
    public Map<String, Object> logout(HttpSession session) {
        session.invalidate();
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        return result;
    }

    @GetMapping("/me")
    public Map<String, Object> getCurrentUser(HttpSession session) {
        User user = (User) session.getAttribute("user");
        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            result.put("success", true);
            result.put("user", user);
        } else {
            result.put("success", false);
            result.put("message", "未登录");
        }
        return result;
    }

    @PostMapping("/change-password")
    public Map<String, Object> changePassword(@RequestBody Map<String, String> form, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Map<String, Object> result = new HashMap<>();
        if (user == null) {
            result.put("success", false);
            result.put("message", "未登录");
            return result;
        }
        String oldPwd = form.get("oldPassword");
        String newPwd = form.get("newPassword");
        if (!userService.checkPassword(user, oldPwd)) {
            result.put("success", false);
            result.put("message", "原密码错误");
            return result;
        }
        userService.updatePassword(user.getId(), newPwd);
        result.put("success", true);
        return result;
    }
}
